<template>
  <div class="bind-phone">
    <nav-bar :title="headerTitle"></nav-bar>
    <div class="main">
      <van-cell-group>
        <van-field v-model="phoneNumber" required clearable label="手机号码" placeholder="请输入手机号" />
        <van-field v-model="vCode" center clearable label="验证码" placeholder="请输入短信验证码" >
          <van-button slot="button" size="small" type="primary" @click="handleClick" v-if="!sending">发送验证码</van-button>
          <van-count-down slot="button" format="ss S" :time="time" :auto-start="false" :class="sending?'':'hidden'" ref="countDown" @finish="finish"/>
        </van-field>
      </van-cell-group>
      <van-button type="default" class="pay" @click="handleSubmit">立即绑定</van-button>
    </div>
  </div>
</template>

<script>
import { Field, Button, Cell, CellGroup } from "vant";
Vue.use(Field)
  .use(Button)
  .use(Cell)
  .use(CellGroup);
import { CountDown } from 'vant';
Vue.use(CountDown);
import navBar from "@/components/nav-bar";
import { mapActions } from "vuex";
export default {
  name: "bindPhone",
  data() {
    return {
      headerTitle: "绑定手机",
      time: 60000,
      sending: false,
      phoneNumber: "",
      vCode: ""
    };
  },
  components: { navBar },
  methods: {
    ...mapActions(["getSmsCode", "bindPhone"]),
    handleClick() {
      if(this.sending) return false;
      if (/^[\d]{11}$/.test(this.phoneNumber)) {
        this.getSmsCode({
          mobile: this.phoneNumber
        }).then(res => {
          this.sending = true
          this.$refs.countDown.start();
          window.countDown = this.$refs.countDown
          console.log(window.countDown)
        }).catch(err => {
          window.countDown = this.$refs.countDown
          console.log(err,err.response , window.countDown)
        });
      } else {
        this.$toast('请输入正确的手机号码')
      }
    },
    handleSubmit() {
      if(!this.phoneNumber){
        return  this.$toast('请输入正确的手机号码')
      }
      if(!this.vcode){
        return  this.$toast('请输入验证码')
      }
      this.bindPhone({
        code: this.vcode, 
        mobile: this.phoneNumber
      }).then(res => {
        this.$router.push({ path: "/" });
      });
    },
    finish(){
      this.sending = false
    }
  }
};
</script>

<style lang="less">
* {
  padding: 0;
  margin: 0;
}
.hidden{
  display: none;
}
.van-button--primary {
  background: linear-gradient(
    90deg,
    rgba(1, 47, 64, 1) 0%,
    rgba(1, 47, 64, 1) 100%
  );
  border: 0.026667rem solid rgba(1, 47, 64, 1);
}
.bind-phone {
  position: relative;
  padding-top: 100px;
  box-sizing: border-box;
  height: 100vh;
  width: 100vw;
  .main {
    .pay {
      position: absolute;
      left: 50%;
      top: 50%;
      width: 333px;
      color: #fff;
      transform: translateX(-50%);
      background: linear-gradient(
        90deg,
        rgba(1, 47, 64, 1) 0%,
        rgba(1, 47, 64, 1) 100%
      );
    }
  }
}
</style>
